package com.szrt.banji09.maven_project03.homework.day1026;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import org.junit.Test;

import com.google.gson.Gson;

public class MySQLDemo {
	/***
	 * jdbc
	 * 1 建立连接
	 * 2 sql 语句
	 * 3 返回结果
	 * @throws Exception
	 */
	@Test
	public void select() throws Exception {
		//加载数据库驱动，这里用到mysql
		Class.forName("com.mysql.jdbc.Driver");
		//url 连接数据库
		String url="jdbc:mysql://127.0.0.1:3306/db1610";
		String user="root";
		String password="root";
		//获取连接，登陆
		Connection connection=DriverManager.getConnection(url, user,password);
		Statement statement=connection.createStatement();
		String sql="SELECT * FROM ca_student_t ";
		ResultSet rs=statement.executeQuery(sql);
		//用list遍历
		ArrayList list = new ArrayList();
		while(rs.next()){
			String name=rs.getString("STUDENT_NAME");
			int id=rs.getInt("ID");
			int age=rs.getInt("STUDENT_AGE");
			StudentEntity student = new StudentEntity(id,age,name);
			list.add(student);
		}
		Gson json = new Gson();
		System.out.println(json.toJson(list));
		// 从result里遍历 
		//5 遍历结果集  从set里面1个1个的遍历   List
		/*while(rs.next()){
			//如何拿到第1列的值   2种方法
			//2.1 用下标访问 下标从1开始 避免使用
			//String xx = rs.getString(2);
			//System.out.println(xx);
			//2.2 直接用字段的名称  自动找出列  自动找出调用列对应的方法(反射...)
			String studentName = rs.getString("STUDENT_NAME");
			int id  = rs.getInt("ID");
			int studentAge = rs.getInt("STUDENT_AGE");
			//int id, int studentAge, String studentName  TeacherEntity
			StudentEntity student = new StudentEntity(id,studentAge,studentName);
			GsonUtil.toJson(student);
			
		}*/
		
	//sonSysOut.sysOut(rs);
	}
}
